<?php

namespace App\Kuafu\CustomerCoupon\Jobs;

use App\Kuafu\Common\Jobs\SensorsDataJob;
use App\Kuafu\Common\Service\CommonService;
use App\Kuafu\Coupon\Enum\CouponEnum;
use App\Kuafu\Coupon\Model\CouponModel;
use App\Kuafu\CouponPackage\Model\CouponPackageModel;
use App\Kuafu\CouponPackage\Model\CouponPackageOrderModel;
use App\Kuafu\Customer\Service\CustomerPlatformService;
use App\Kuafu\CustomerCoupon\Enum\CodeEnum;
use App\Kuafu\CustomerCoupon\Model\CustomerCouponModel;
use App\Kuafu\Order\Model\OrderExternalSplitModel;
use App\Kuafu\Wechat\Service\WechatSendMessageService;
use App\Library\FeiShu\SendFs;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

/**
 * @description 领取优惠券消费队列
 *
 * @queueName {RMS-RECEIVE-COUPON-QUEUE}
 */
class ReceiveCouponJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * 异常标题
     */
    const EXCEPTION_TITLE = '【消费队列】【领取优惠券】';

    /**
     * 队列名称
     *
     * @var string
     */
    public static string $QUEUE_NAME = '{RMS-RECEIVE-COUPON-QUEUE}';

    /**
     * 门店id
     *
     * @var int
     */
    public int $shopId;

    public int $targetId;

    /**
     * 券来源
     *
     * @var string
     */
    public string $source;

    /**
     * 用户优惠券id
     *
     * @var int
     */
    public int $userCouponId;

    /**
     * @var int 券包购买类型
     */
    public int $type;

    public string $couponPackageOrderId;

    /**
     * 批量发券ids
     *
     * @var array
     */
    public array $batchCouponIds;


    const TYPE_ACTIVITY       = 1;
    const TYPE_COUPON_PACKAGE = 2;

    const TYPE_TEXT = [
        self::TYPE_ACTIVITY       => '店内活动',
        self::TYPE_COUPON_PACKAGE => '[ %s ] 券包购买'
    ];

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(
        $shopId,
        $targetId,
        $type,
        $couponPackageOrderId,
        $source,
        $userCouponId,
        $batchCouponIds
    ) {
        $this->shopId               = $shopId;
        $this->targetId             = $targetId;
        $this->type                 = $type;
        $this->couponPackageOrderId = $couponPackageOrderId;
        $this->source               = $source;
        $this->userCouponId         = $userCouponId;
        $this->batchCouponIds       = $batchCouponIds;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            //神策打点 - 领取优惠券
            $this->sensorsDataHandle();

            //优惠券提醒
            $this->couponRemind($this->shopId);

            //神策打点 - 券包购买
            $this->sensorsCouponPackageHandle();

        } catch (Exception $e) {
            CommonService::fsLogException(self::EXCEPTION_TITLE, $e,
                Collect(get_object_vars($this))->only(['shopId', 'userCouponId', 'source', 'queue'])->toArray(), true);
        }
    }

    /**
     * 神策打点 - 优惠券券包购买
     */
    public function sensorsCouponPackageHandle()
    {
        if ($this->batchCouponIds) {
            switch ($this->type) {
                case self::TYPE_COUPON_PACKAGE:
//                    $couponPackageOrder = CouponPackageOrderModel::query()->with([
//                        'couponPackageRel' => function ($query) {
//                            $query->with(['couponPackageMappingRel']);
//                        }
//                    ])->where('orderId', $this->couponPackageOrderId)->first();
//                    if ($couponPackageOrder) {
//                        //丢入神策埋点
//                        SensorsDataJob::dispatch(
//                            $this->shopId,
//                            $couponPackageOrder->userId,
//                            SensorsDataJob::TYPE_BUY_COUPON_PACKAGE,
//                            [
//                                //业务场景
//                                'collect_scene'     => $this->source,
//                                //券包id
//                                'couponBag_id'      => $couponPackageOrder->couponPackageId,
//                                //券包收音也是文案
//                                'couponBag__name'   => $couponPackageOrder->couponPackageRel->publicityCopy,
//                                //券包名称
//                                'couponBag_content' => $couponPackageOrder->couponPackageRel->name,
//                                //券包数量
//                                'coupon_quantity'   => $couponPackageOrder->couponPackageRel->couponPackageMappingRel->count(),
//                                //券包售价
//                                'couponBag__amount' => bcdiv($couponPackageOrder->couponPackageRel->salePrice, 100, 2),
//                            ]
//                        )->onQueue(SensorsDataJob::$QUEUE_NAME);
//                    }
                    break;
            }
        }
    }

    /**
     * 神策埋点处理
     *
     * @throws Exception
     */
    public function sensorsDataHandle()
    {
//        $userCouponObject = CustomerCouponModel::query()->where('id', $this->userCouponId)->first();
//        if (empty($userCouponObject)) {
//            throw new Exception('用户优惠券不存在');
//        }

//        $couponPackage = null;
//        if ($this->type == self::TYPE_COUPON_PACKAGE && $this->targetId > 0) {
//            $couponPackage = CouponPackageModel::query()->where('id', $this->targetId)->first();
//        }

        //丢入神策埋点
//        SensorsDataJob::dispatch(
//            $this->shopId,
//            $userCouponObject->userId,
//            SensorsDataJob::TYPE_RECEIVE_COUPON,
//            [
//                'access_way'        => empty($this->couponPackageOrderId) ? '领取' : '购买',
//                //领取场景 STRING 弹窗
//                'collect_scene'     => $this->source,
//                //用户优惠券id string
//                'user_coupon_id'    => $this->userCouponId,
//                //优惠券id STRING
//                'coupon_id'         => $userCouponObject->couponId,
//                //优惠券类型 STRING 折扣券，满减券
//                'coupon_type'       => CouponEnum::COUPONTYPE[$userCouponObject->couponType],
//                //优惠券名称 STRING 新人优惠券
//                'coupon_name'       => $userCouponObject->name,
//                //优惠券内容 STRING 满xx减xx
//                'coupon_content'    => CouponModel::getCouponDescription(
//                    $userCouponObject->couponType,
//                    $userCouponObject->discount,
//                    $userCouponObject->useCondition
//                ),
//                //优惠券金额 NUMBER 券面值
//                'coupon_amount'     => $userCouponObject->couponType == CouponEnum::COUPON_TYPE_VOUCHERS ? bcdiv($userCouponObject->discount,
//                    100, 2) : 0,
//                //优惠券折扣 STRING 6.8折
//                'coupon_discount'   => $userCouponObject->couponType == CouponEnum::COUPON_TYPE_DISCOUNT ? $userCouponObject->discount : 0,
//                'coupon_period'     => (string)(int)(($userCouponObject->endAt - $userCouponObject->startAt) / (24 * 60 * 60)),
//                'coupon_startDate'  => date('Y-m-d H:i:s', $userCouponObject->startAt),
//                'coupon_endDate'    => date('Y-m-d H:i:s', $userCouponObject->endAt),
//                'couponBag_id'      => $couponPackage ? $this->targetId : '',
//                'couponBag__name'   => $couponPackage ? $couponPackage->publicityCopy : '',
//                'couponBag_content' => $couponPackage ? $couponPackage->name : '',
//            ]
//        )->onQueue(SensorsDataJob::$QUEUE_NAME);
    }

    /**
     * 优惠券提醒
     * @param int $shopId
     */
    public function couponRemind(int $shopId)
    {
        if ($this->batchCouponIds) {
            $customerCoupons = CustomerCouponModel::query()->whereIn('id', $this->batchCouponIds)->select([
                'userId',
                'name',
                'startAt',
                'endAt',
                'isExpireNotice',
                'isArrivalNotice',
                'expireNoticeDay'
            ])->get();

            $couponLists = $customerCoupons->map(function ($v) {
                if ($v->isExpireNotice == CodeEnum::EXPIRE_NOTICE_YES || $v->isArrivalNotice == CodeEnum::ARRIVAL_NOTICE_YES) {
                    $noticeTime          = $v->endAt - (24 * 60 * 60 * $v->expireNoticeDay);
                    $v->noticeTime       = $noticeTime;
                    $v->noticeDate       = date('Y-m-d', $noticeTime);
                    $v->noticeFormatTime = strtotime(date('Y-m-d', $noticeTime) . ' 17:00:00');
                    return $v;
                }
            })->filter()->values();

            //券到账提醒
            $arrivalNoticeCount = $couponLists->where('isArrivalNotice', '=', CodeEnum::ARRIVAL_NOTICE_YES)->count();
            if (config('app.env') == 'qa') {
                SendFs::newRobot()
                      ->setTitleContent('优惠券到账', $customerCoupons->toJson(JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT))
                      ->send();
            }
            if ($arrivalNoticeCount > 0) {
                //查询用户openId
                $platformId = 1;
                $userOpenId = CustomerPlatformService::getUserFieldByUserId(
                    $couponLists->getIterator()->current()->userId,
                    $platformId,
                    ['openid']
                );
                if ($userOpenId) {
                    WechatSendMessageService::couponArrivalNoticeSendMessage(
                        $couponLists->where('isArrivalNotice', '=', CodeEnum::ARRIVAL_NOTICE_YES)->getIterator()
                                    ->current()->name,
                        $couponLists->where('isArrivalNotice', '=', CodeEnum::ARRIVAL_NOTICE_YES)->sortBy('startAt')
                                    ->first()->startAt,
                        $couponLists->where('isArrivalNotice', '=', CodeEnum::ARRIVAL_NOTICE_YES)->sortByDesc('startAt')
                                    ->first()->endAt,
                        vsprintf("您有%d张优惠券到账了，请尽快使用", [$arrivalNoticeCount]),
                        $userOpenId->openid,
                        $shopId
                    );
                }
            }
        }
    }
}
